package com.cskaoyan.gateway.controller.shopping;

import com.cskaoyan.gateway.bo.TrolleyAddBo;
import com.cskaoyan.gateway.bo.TrolleyBo;
import com.cskaoyan.gateway.utils.TokenUtil;
import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.shopping.ICartService;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.dto.*;
import com.mall.user.annotation.Anoymous;
import lombok.extern.slf4j.Slf4j;
//import org.apache.catalina.security.SecurityUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.zookeeper.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Member;

/**
 * @author XuBang
 * @TODO: 1.获得购物车列表 2.添加商品到购物车 3.更新购物车中的商品 by xubang
 * @date 2021/10/31$
 * @trainOfthought:
 */
//@Slf4j
@RestController
@RequestMapping("/shopping")
public class TrolleyController {

    //远程调用 & 引用服务
    @Reference(timeout = 3000, retries = 0, check = false)
    ICartService iCartService;

    //controller层（核心逻辑）：调用service层

    /**
     * 1.获得购物车列表
     *
     * @return 请求路径：/shopping/carts
     * 是否需要携带Token：是
     * 请求类型：get
     */
    @GetMapping("/carts")
//    @Anoymous
    public ResponseData listGet(HttpServletRequest servletRequest) {
        //1.获取前端的请求参数（Request校验封装：请求参数）
        CartListByIdRequest request = new CartListByIdRequest();


        /**
         * 从订单模块获取的灵感：使用一个内置自定义工具类获取userId
         */
        // 获取token令牌并解析获取userId
        //在调用之前，赋值即可；赋值放在远程调用service层
//        /**
//         * 从订单模块获取的灵感：使用一个内置自定义工具类获取userId
//         */
//        // 获取token令牌并解析获取userId
//        Long userId = TokenUtil.getUserId(servletRequest);
//        request.setUserId(userId);

        //4.调用service层
        CartListByIdResponse cartListById = iCartService.getCartListById(request);   //出入携带userId的request

        //*************上述逻辑正确；下方的响应，一会检查：检查，不存在问题*******************

        //5.返回ResponseData数据类型（对返回的Response状态码进行校验，ResponseUtil进一步封装，响应前端）
        if (ShoppingRetCode.SUCCESS.getCode().equals(cartListById.getCode())) {
            return new ResponseUtil().setData(cartListById.getCartProductDtos());
        }

        return new ResponseUtil().setErrorMsg(cartListById.getMsg());
    }


    /**
     * 测试正常
     */

    /**
     * 2.添加商品到购物车
     *
     * @return 请求路径：/shopping/carts
     * 是否需要携带Token：是
     * 请求类型：post
     * 请求参数示例：
     * {"userId":"62","productId":100053202,"productNum":1}
     */
    @PostMapping("/carts")
    public ResponseData cartAdd(@RequestBody(required = false) TrolleyAddBo trolleyAddBo) {
        //System.out.println("controller:"+trolleyAddBo.getUserId()+trolleyAddBo.getProductId()+trolleyAddBo.getProductNum());

        //1.获取前端的请求参数（Request校验封装：请求参数）-----字段不一致，需要进行转化
        AddCartRequest request = new AddCartRequest();

        request.setUserId(trolleyAddBo.getUserId().longValue());
        request.setItemId(trolleyAddBo.getProductId().longValue());
        request.setNum(trolleyAddBo.getProductNum());

        //2.调用service层
        AddCartResponse response = iCartService.addToCart(request);


        //************************上述检查，没有问题；一会回过头，检查下方的返回；检查完毕；木有问题****************************

        //3.返回ResponseData数据类型（对返回的Response状态码进行校验，ResponseUtil进一步封装，响应前端）
        if (ShoppingRetCode.SUCCESS.getCode().equals(response.getCode())) {
            return new ResponseUtil().setData(response.getResult());     //***********此处对比过，没有问题********
        }
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }


    /**
     * 3.更新购物车中的商品
     *
     * @param trolleyBo
     * @return
     */
    @RequestMapping(value = "/carts", method = RequestMethod.PUT)
    public ResponseData cartUpdate(@RequestBody(required = false) TrolleyBo trolleyBo) {
        //1.获取前端的请求参数（Request校验封装：请求参数）-----字段不一致，需要进行转化
        UpdateCartNumRequest request = new UpdateCartNumRequest();
        request.setChecked(trolleyBo.getChecked());
        request.setItemId(trolleyBo.getProductId());
        request.setNum(trolleyBo.getProductNum());
        request.setUserId(trolleyBo.getUserId());

        //2.调用service层：传入校验后的请求参数request；获取response
        UpdateCartNumResponse response = iCartService.updateCartNum(request);

        //*******************上方没有问题，下方一会检查一下**************************************************

        //3.返回ResponseData数据类型（对返回的Response状态码进行校验，ResponseUtil进一步封装，响应前端）
        if (ShoppingRetCode.SUCCESS.getCode().equals(response.getCode())) {
            return new ResponseUtil().setData(response.getResult());
        }
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }

    /**
     * auther:yangwenjian
     * Todo: 10.删除购物车中的商品
     * date: 2021/11/01
     */
    @DeleteMapping("/carts/{uid}/{pid}")
    public ResponseData deleteCartItem(@PathVariable("uid") Long uid, @PathVariable("pid") Long pid) {
        DeleteCartItemRequest request = new DeleteCartItemRequest();
        uid = new Long(uid);
        pid = new Long(pid);
        request.setUserId(uid);
        request.setItemId(pid);
        DeleteCartItemResponse response = iCartService.deleteCartItem(request);

        if (response.getCode().equals((ShoppingRetCode.SUCCESS.getCode()))) {
            return new ResponseUtil<>().setData(response.getMsg());
        }
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }

    /**
     * auther: yangwenjian
     * todo: 11.删除购物车中选中的商品
     * date：2021/11/01
     */
    @DeleteMapping("items/{uid}")
    public ResponseData deleteCheckedItem(@PathVariable("uid") Long uid) {
        DeleteCheckedItemRequest request = new DeleteCheckedItemRequest();
        request.setUserId(uid);
        DeleteCheckedItemResposne resposne = iCartService.deleteCheckedItem(request);
        if (ShoppingRetCode.SUCCESS.getCode().equals(resposne.getCode())) {
            return new ResponseUtil<>().setData(ShoppingRetCode.SUCCESS.getMessage());
        }
        return new ResponseUtil<>().setData("失败");
    }

    /**
     * auther: yangwenjian
     * todo: 12.全选购物车中的商品
     * date: 2021/11/01
     */
    @PutMapping("/items")
    public ResponseData checkAllCartItem(@RequestParam(value = "userId") Long userId,
                                         @RequestParam(value = "checked") String checked) {
        CheckAllItemRequest request = new CheckAllItemRequest();
        request.setUserId(userId);
        request.setChecked(checked);
        CheckAllItemResponse response = iCartService.checkAllCartItem(request);
        if (response.getCode().equals(ShoppingRetCode.SUCCESS.getCode())) {
            return new ResponseUtil<>().setData(response.getMsg());
        }
        return new ResponseUtil<>().setErrorMsg(response.getMsg());

    }

}